<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" placeholder="输入员工姓名全员搜索" prefix-icon="el-icon-search" size="small" style="margin-bottom:10px" type="text" @input="changeValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptRef" :data="depts" :expand-on-click-node="false" :props="defaultProps" default-expand-all highlight-current node-key="id" @node-click="clickHandler" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" justify="end" type="flex">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployeeExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table ref="multipleTable" :data="empList" style="width: 100%" tooltip-effect="dark">
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column align="center" label="头像" prop="" width="80">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" size="small" />
              <span v-else class="username">{{ row.username.substring(0, 1) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="姓名" prop="username" width="120" />
          <el-table-column align="center" label="手机号" prop="mobile" sortable width="200" />
          <el-table-column align="center" label="工号" prop="workNumber" sortable width="200" />
          <el-table-column align="center" label="聘用形式" prop="formOfEmployment" width="120">
            <template v-slot="{ row }">
              <el-tag :type="row.formOfEmployment === 1 ? 'success' : 'info'">
                {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="部门" prop="departmentName" width="200" />
          <el-table-column align="center" label="入职时间" prop="timeOfEntry" sortable width="200" />
          <el-table-column align="center" label="操作" width="280">
            <template v-slot="{ row }">
              <el-button size="small" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" @click="distributeEmployee(row)">角色</el-button>
              <el-popconfirm title="您确定要删除该员工吗？" @confirm="deleteEmployee(row)">
                <template v-slot:reference>
                  <el-button size="mini" style="margin-left: 10px">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row justify="center" style="margin-top: 10px" type="flex">
          <el-pagination :current-page="queryParams.page" :page-size="queryParams.pagesize" :total="queryParams.total" layout="total, prev, pager, next" @current-change="currentChange" />
        </el-row>
      </div>
    </div>
    <!--导入上传excel组件-->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!--分配角色权限弹框-->
    <el-dialog :visible.sync="showDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row justify="center" style="margin-top: 20px" type="flex">
        <el-button size="mini" @click="cancel">取消</el-button>
        <el-button size="mini" type="primary" @click="confirmDistribute">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { transListToTreeData } from '@/utils'
import { getDepartmentList } from '@/api/department'
import {
  deleteEmployeeById,
  distributeRoleForEmployee,
  exportEmployeeExcel,
  getEmployeeById,
  getEmployeeList
} from '@/api/employee'
import fileSaver from 'file-saver/dist/FileSaver'
import ImportExcel from '@/views/employee/components/import-excel.vue'
import { getEnableRoleList } from '@/api/role'

export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      roleList: [], // 存储已启用的角色列表
      showDialog: false, // 显示或关闭分配角色的对话框的标记
      roleIds: [], // 存储复选框选中的值
      currentEmployeeId: null, // 当前员工id
      depts: [], // 部门列表
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      empList: [], // 员工列表
      // 查询参数
      queryParams: {
        page: 1, // 当前页码数
        pagesize: 10, // 当前页面需要的数据条数
        keyword: '', // 根据名字模糊查询
        departmentId: null, // 部门id,根据部门查询当前部门及子部门的用户
        total: 0
      },
      // 定义开启上传excel组件的弹框
      showExcelDialog: false
    }
  },
  created() {
    this.getDepartmentList()
    this.getEnableRole()
  },
  methods: {
    // 获取组织架构
    async getDepartmentList() {
      const res = await getDepartmentList()
      this.depts = transListToTreeData(res, 0)
      // 记录节点id
      this.queryParams.departmentId = this.depts[0].id
      // tree组件的渲染是异步的，需要等待Dom节点渲染完毕之后，使用this.$nextTick()方法
      this.$nextTick(() => {
        this.$refs.deptRef.setCurrentKey(this.queryParams.departmentId)
      })
      await this.getEmployeeList()
    },

    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.queryParams.total = total
      this.empList = rows
    },

    // 点击树节点事件
    clickHandler(node) {
      // 点击树节点时记录节点id
      this.queryParams.departmentId = node.id
      // 当id改变时需要从第一页开始检索
      this.queryParams.page = 1
      this.getEmployeeList()
    },

    // 输入框查询功能
    changeValue() {
      // 防抖处理
      // 清除定时器
      clearTimeout(this.tiemr)
      this.tiemr = setTimeout(() => {
        // 当值改变时从第一页开始检索
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },

    // 分页功能
    // 当前页码改变时触发，左右按钮被点击也会触发这个事件
    currentChange(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList()
    },

    // 导出员工excel
    async exportEmployeeExcel() {
      const blob = await exportEmployeeExcel()
      /**
       * 语法
       * FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })
       * 参数1：下载的文件
       * 参数2：下载的文件类型
       * 参数3：可选参数
       */
      fileSaver.saveAs(blob, '员工信息标.xlsx')
    },

    async getEnableRole() {
      // 获取已启用角色列表
      this.roleList = await getEnableRoleList()
    },

    // 点击分配角色按钮
    async distributeEmployee(row) {
      this.currentEmployeeId = row.id
      const { roleIds } = await getEmployeeById(this.currentEmployeeId)
      this.roleIds = roleIds
      this.showDialog = true // 获取完数据再显示弹窗
    },
    // 分配角色取消按钮
    cancel() {
      this.showDialog = false
    },

    // 分配角色确定按钮
    async confirmDistribute() {
      // 调用给员工分配角色接口
      await distributeRoleForEmployee({ id: this.currentEmployeeId, roleIds: this.roleIds })
      // 提示成功信息
      this.$message.success('为员工分配角色成功！')
      // 关闭弹框
      this.cancel()
    },

    // 删除员工
    async deleteEmployee(row) {
      await deleteEmployeeById(row.id)
      // 判断当前页删除的是不是最后一个，// 如果是最后一个，当前页码减一位
      if (this.empList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.$message.success('删除员工成功')
      await this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }

  ::v-deep .el-table__header th {
    background-color: #f5f6f8;
  }
}

</style>
